package MeteoCal.manager;

import MeteoCal.entity.Event;
import MeteoCal.entity.Group;
import MeteoCal.entity.Schedule;
import MeteoCal.entity.User;
import java.security.Principal;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import javax.ejb.Stateless;
import javax.inject.Inject;
import javax.persistence.EntityExistsException;
import javax.persistence.EntityManager;
import javax.persistence.FlushModeType;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
import net.fortuna.ical4j.model.component.VEvent;

/**
 *
 * @authors Guttadoro, Iommazzo, Saullo
 */
@Stateless
public class UserManager {

    @PersistenceContext
    private EntityManager em;
    
    @Inject
    Principal principal;
    
    public void saveUser(User u){
        em.merge(u);
        em.flush();
    }

    public Boolean save(User user,Schedule schedule) {
     
            user.setType(Group.USER);
            if(em.find(User.class,user.getEmail()) != null)
                return false;
            em.persist(schedule);
            user.setIdSchedule(schedule);
            em.persist(user);
            return true;
       
    }

    public void update(User user){
        em.setFlushMode(FlushModeType.AUTO);
        em.merge(user);
        em.flush();
    }
    
    public void unregister() {
        em.remove(getLoggedUser());
    }

    public User getLoggedUser() {
        //return em.find(User.class, "daniele.guttadoro@gmail.com");
        return em.find(User.class, principal.getName());
    }
    
    public List<User> getUsers() {     
       return em.createNamedQuery("User.findAll", User.class).getResultList();
             
    }

    public User getUserByEmail(String email) {
        return em.find(User.class, email);
        
    } 
        
    public List<Event> cloneL(Collection<Event> list) {
        if (list==null) return null;
            List<Event> clone = new ArrayList<>(list.size());
            for(Event item: list) 
                clone.add(new Event(item));
            return clone;
    }

//    public Event obtainEvent(VEvent event) {
//        TypedQuery<Event> query = em.createNamedQuery("Event.findByIdEvent", Event.class);
//        query.setParameter("idEvent",Integer.parseInt(event.getUid().getValue()));
//        try{
//            Event e = query.getSingleResult();
//            if(!e.getName().equals(event.getSummary().getValue()))
//                return null;
//            return e;
//        } catch (NoResultException e){
//            return null;
//        }
//    }

    public void addParticipant(Event e, User loggedUser) {
        e.getScheduleCollection().add(loggedUser.getIdSchedule());
        em.merge(e);
        em.flush();
    }

    public List<User> search(String searchString) {
        return this.getUserByName(searchString);
    }
    
    private List<User> getUserByName(String name){
        
        TypedQuery<User> query = em.createNamedQuery("User.findByName", User.class);
        query.setParameter("name", name);
        List<User> list = query.getResultList();
        
        TypedQuery<User> query2 = em.createNamedQuery("User.findBySurname", User.class);
        query2.setParameter("surname", name);
        list.addAll(query2.getResultList());
        
        return list;
    }
    
    public Collection getEventDay(Date date) {
        
        
        //I obtain the instance of user
        User user = this.getLoggedUser();
        
        //I look for all events related to his own idschedule
        Schedule schedule = getSchedulebyId(user); 
        
        List<Event> eventsClone = this.cloneL(schedule.getEventCollection());

        return eventsInDate(eventsClone,date);
        
    }
    
    private Schedule getSchedulebyId(User user) {
        
        TypedQuery<Schedule> query2 = em.createNamedQuery("Schedule.findByIdSchedule", Schedule.class);
        query2.setParameter("idSchedule", user.getIdSchedule().getIdSchedule());
        
        return query2.getSingleResult();
    }
    
    private Collection eventsInDate(Collection<Event> events, Date day) {
        
        List<Event> result = new ArrayList<>();
        for(Event item: events){
            Date datebeg = item.getDateBegin();
            if(datebeg.equals(day)){
                    result.add(item);
            }
        }
    
        return result;
    }

}
